<template>
  <!-- 表单 -->
  <el-form :inline="true" :model="ruleForm" :rules="rules" ref="ruleForm" size="small"
           label-width="auto" class="search-form">

    <!-- S/N -->
    <el-form-item label="S/N：" prop="sn" v-if="showAll">
      <el-input v-model="ruleForm.sn" placeholder="请输入序列号"></el-input>
    </el-form-item>

    <!-- 区域 -->
    <!--@active-item-change="handleItemChange"-->
    <!--<el-form-item label="区域：" prop="area">-->
    <!--  <el-cascader-->
    <!--      placeholder="请选择区域"-->
    <!--      v-model="ruleForm.area"-->
    <!--      :props="props"-->
    <!--      :options="provenceArray"-->
    <!--  ></el-cascader>-->
    <!--</el-form-item>-->

    <el-form-item label="区域：" prop="area">
      <el-cascader
          @focus="getAreaList"
          placeholder="请选择区域"
          v-model="ruleForm.area"
          :options="areaOptions"
          :key="key"
      ></el-cascader>
    </el-form-item>

    <!-- 配置状态 -->
    <el-form-item label="配置状态：" prop="status" v-if="name==='Config'">
      <el-select v-model="ruleForm.status" placeholder="请选择状态">
        <el-option label="全部" value="1"></el-option>
        <el-option label="可配置" value="2"></el-option>
        <el-option label="无法配置" value=""></el-option>
      </el-select>
    </el-form-item>

    <!-- 状态 -->
    <el-form-item label="状态：" prop="status" v-else>
      <el-select v-model="ruleForm.status" placeholder="请选择状态">
        <el-option label="全部  " value=""></el-option>
        <el-option label="在线" value="1"></el-option>
        <el-option label="离线" value="2"></el-option>
      </el-select>
    </el-form-item>

    <!-- 点位号 -->
    <el-form-item label="点位：" prop="point" v-if="showAll">
      <el-input v-model="ruleForm.point" placeholder="请输入点位号"></el-input>
    </el-form-item>

    <!-- 按钮 -->
    <el-form-item>
      <a-button type="primary" class="search-btn" @click="submitForm()">查询</a-button>
      <a-button @click="resetForm('ruleForm')">重置</a-button>
      <a-button v-if="showAll" class="export-btn">
        <a href="javascript:void(0);" @click="exportExcel" ref="exportLink">导出</a>
      </a-button>
    </el-form-item>
  </el-form>
</template>

<script>

import base from '@/api/modules/equipment/base';

export default {
  name: 'searchForm',
  props: {
    showAll: {
      required: false,
      type: Boolean,
      default: () => true
    },
    name: {
      required: true,
      type: String,
      default: () => ''
    },
    page: {
      required: true,
      type: Number,
      default: () => 1
    }
  },
  watch: {
    page: {
      immediate: true,
      handler: function(newVal, oldVal) {
        // console.log(newVal, oldVal);
        if (oldVal !== undefined) {
          this.submitForm(newVal);
        }
      }
    }
  },
  data() {
    return {
      // 点位数组
      areaOptions: [],

      key: 0,

      // 表单数据
      ruleForm: {
        sn: '',
        area: [],
        status: '',
        point: ''
      },
      // 表单验证
      rules: {
        sn: [
          { message: '请输入活动名称', trigger: 'blur' },
          { min: 1, max: 100, message: '长度为 5 个字符', trigger: 'blur' }
        ],
        status: [
          { message: '请选择状态', trigger: 'change' }
        ],
        point: [
          { message: '请选择点位', trigger: 'blur' }
        ]
      },
      provenceArray: [],
      // props: {
      //   label: 'areaName',
      //   value: 'areaId',
      //   children: 'cities'
      // },
      props: {
        lazy: true,
        lazyLoad: (node, resolve) => {
          // 取出当前信息
          const { level, value } = node;
          // 请求下一级
          this.$api.common.getArea({
            searchParentCode: value || ''
          })
            .then(res => {
              // console.log(res.data.data.list)
              let list = res.data.data.list;
              const nodes = list.map(item => {
                // const num = this.tools.getRandom(1, 2)
                return {
                  value: item.code,
                  label: item.name,
                  // leaf: num === 2
                };
              });
              // 返回
              resolve(nodes);
            });
        }
      },
    };
  },
  methods: {
    // 获取区域位置
    async getAreaList() {

      // 判断区域数组是否为空,不为空，不往后执行
      if (this.areaOptions.length > 0) {
        return;
      }

      const res = await this.$api.common.getArea();
      // console.log(res);
      if (res.data.status) {
        let data = res.data.data.reduce((prev, tar) => {
          // console.log(tar);
          prev.push({
            value: tar.code,
            label: tar.name,
            pValue: tar.parentCode
          });
          return prev;
        }, []);

        this.areaOptions = this.tools.splitTree(data, 'value', 'pValue');
      }
    },

    // 提交表单
    submitForm(index = 1) {
      // 处理参数，只传点位数组的最后一个
      let area = this.ruleForm.area.pop() || '';
      let a;
      // 判断是不是配置的
      if (this.name === 'Config') {
        a = {
          searchConfigStatus: parseInt(this.ruleForm.status) || '',
          searchDistrictCode: area,
          index
        };
      } else {
        a = {
          searchDeviceStatus: parseInt(this.ruleForm.status) || null,
          searchSerialId: this.ruleForm.sn,
          searchDistrictCode: area,
          searchPointId: this.ruleForm.point,
          index
        };
      }
      // 向后台发送参数
      this.$api.equipment[`get${this.name}Table`](a)
        .then(res => {
          console.log(res, '子组件获取', index);
          if (res.data.status) {
            let data, total;
            if (this.name === 'Config') {
              // 表格数据
              data = res.data.data;
              total = res.data.data.length;
            } else {
              // 表格数据
              data = res.data.data.pageDto.records;
              // 总条数
              total = res.data.data.pageDto.totalRecords;
            }

            // this.$parent.tableData = data;
            // this.$parent.total = total
            // 获取表格数据
            this.$emit('getSearchTable', data);
            // 获取总条数
            this.$emit('getSearchPage', total);
          }
        });

      // this.$message.success("查询成功");
    },

    // 重置表单
    resetForm(formName) {
      this.$refs[formName].resetFields();
      // 调用父级的方法，改变页码为 1
      this.$parent.getTable();
      this.$parent.clearTable();
      this.$emit('getCurrentPage', 1);
      // this.areaOptions = [];
      this.key++;
      // this.$emit("handleCurrentChange", 1)
    },

    // 导出excel
    exportExcel() {
      let host = base.prod;
      let path;
      // console.log(host)
      switch (this.name) {
      case '1024':
        path = '/excel/downloadBDevice';
        break;
      case '430':
        path = '/excel/downloadFDevice';
        break;
      case 'T300':
        path = '/excel/downloadTDevice';
        break;
      case 'Other':
        path = '/excel/downloadHDevice';
        break;
      default:
        this.$message.error('错误，请刷新重试');
        break;
      }

      // 拼接参数
      let arg = `?searchSerialId=${this.ruleForm.sn}&searchDistrictCode=${this.ruleForm.area}&searchDeviceStatus=${this.ruleForm.status || ''}&searchPointId=${this.ruleForm.point}`;

      this.$refs.exportLink.href = `${host}${path}${arg}`;

      console.log(`${host}${path}${arg}`);

      this.$message.success('文件下载中，请查看浏览器的下载中心');

      // this.$api.index[`get${this.name}Export`]({
      //   searchSerialId: this.ruleForm.sn || null,
      //   searchDistrictCode: this.ruleForm.area || null,
      //   searchDeviceStatus: parseInt(this.ruleForm.status) || null,
      //   searchPointId: this.ruleForm.point || null
      // })
      //   .then(res => {
      //     console.log(res)
      //     window.open()
      //   })
    }
  },
  created() {
    // console.log(this.name);
  }
};
</script>

<style scoped lang="less">
  @import "~@/assets/css/equipment.less";

  .export-btn {
    a {
      display: block;
      width: 100%;
      font-size: 14px;
      font-family: "sans-serif;" !important;
    }
  }

  /deep/ .el-input__inner {
    width: 262px;
  }
</style>
